package org.lingshi.security;

import net.sf.json.JSONObject;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest req, HttpServletResponse resp, AccessDeniedException e)
            throws IOException, ServletException {
        String header = req.getHeader("X-Requested-With");
        if(header != null && "XMLHttpRequest".equals(header)){
            resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
            resp.setContentType("application/json;charset=UTF-8");
            resp.sendError(403);
            resp.getWriter().write(getJSON(e));
        }else{
            String ctxPath = req.getContextPath();
            resp.sendRedirect(ctxPath+"/errors/403-error.html");
        }
    }
    private String getJSON(AccessDeniedException e){
        JSONObject jsObj = new JSONObject();
        jsObj.put("result","failed");
        jsObj.put("cause","你没有权限访问当前资源");
        jsObj.put("code",403);
        return jsObj.toString();
    }

}
